<template>
  <!-- 搜索及操作区域 -->
  <x-search>
    <template #search>
      <a-select
        v-model:value="program_id"
        placeholder="查询专业"
        style="width: 150px; margin-left: 10px"
        @change="select_pro"
      >
        <a-select-option
          v-for="(item, index) in all_programs"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>

      <a-select
        v-model:value="class_id"
        placeholder="查询班级"
        style="width: 150px; margin-left: 10px"
        @change="get_exams"
      >
        <a-select-option
          v-for="(item, index) in all_classes"
          :key="index"
          :value="item.id"

        >
          {{ item.name }}
        </a-select-option>
      </a-select>

      <a-select
        v-model:value="exam_id"
        placeholder="查询考试(针对成绩表)"
        style="width: 180px; margin-left: 10px"
      >
        <a-select-option
          v-for="(item, index) in all_exams"
          :key="index"
          :value="item.id"
        >
          {{ item.name }}
        </a-select-option>
      </a-select>

      <a-range-picker
        v-model:value="inspect_date"
        style="width: 250px; margin-left: 10px"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
      <a-button type="primary" style="margin-left: 10px" @click="search_data">
        搜索
      </a-button>
      <a-button style="margin-left: 10px" @click="resetSearch"> 重置 </a-button>
    </template>
  </x-search>

  <!-- 统计图部分2个 -->
  <div class="chart1">
    <!-- 学生作业提交趋势统计图 -->
    <x-card :message="message1" :width="49" :height="height1">
      <div ref="chartRef1" style="width: 100%; height: 300px"></div>
    </x-card>

    <!-- 出勤率分布图 -->
    <x-card :message="message2" :width="49" :height="height1">
      <div ref="chartRef2" style="width: 100%; height: 300px"></div>
    </x-card>
  </div>

  <!-- 统计图部分2个 -->
  <div class="chart2">
    <!-- 学生作业提交趋势统计图 -->
    <x-card :message="message3" :width="49" :height="height1">
      <div ref="chartRef3" style="width: 100%; height: 300px; padding: 0"></div>
    </x-card>

    <!-- 作业难度热力分布图 -->
    <x-card :message="message4" :width="49" :height="height1">
      <div ref="chartRef4" style="width: 100%; height: 300px"></div>
    </x-card>
  </div>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, h } from "vue";
import type { Rule } from "ant-design-vue/es/form";
import { message, Modal } from "ant-design-vue";
import {
  EditOutlined,
  DeleteOutlined,
  PlusOutlined,
  DownloadOutlined,
} from "@ant-design/icons-vue";
import dayjs from "dayjs";
import http from "../routerutils/http";
import XSearch from "./XSearch.vue";
import XCard from "./XCard.vue";
import type { Dayjs } from "dayjs";
import * as echarts from "echarts";
import { useRoute } from 'vue-router';

const route = useRoute();
const classId = route.query.class_id; // 直接获取参数
interface ClassInfo {
  id?: number;
  name: string;
}
// 搜索的响应式数据
const class_id = ref();
const exam_id = ref(Number(classId) || undefined);
const program_id = ref();
// 初始化为包含两个 Dayjs 实例的数组
const inspect_date = ref<[Dayjs, Dayjs]>([null, null]);
// 后端接口所有班级数据
const all_classes = ref<ClassInfo[]>([]);
const all_class = async () => {
  try {
    const response = await http.get("/api/students/allclass");
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 后端接口所有专业数据
const all_programs = ref<ClassInfo[]>([]);
const all_program = async () => {
  try {
    const response = await http.get("/api/students/allprogram");
    console.log(response.data.results);
    all_programs.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 选择专业
const select_pro = () => {
  proToclass()
  get_exams()
}
// 根据专业id去获取对应的所以班级
const proToclass = async () => {
  try {
    const response = await http.get("/api/students/pro_class", {
      params: {
        program_id: program_id.value,
      },
    });
    console.log(response.data.results);
    all_classes.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 所有考试表
const all_exams = ref<ClassInfo[]>([]);
const get_exams = async () => {
  try {
    const response = await http.get("/api/students/all_exams", {
      params: {
        class_id: class_id.value,
        program_id: program_id.value,
      },
    });
    console.log(response.data.results);
    all_exams.value = response.data.results;
  } catch (error) {
    console.log("请求失败：：", error);
  }
};
// 搜索的方法
const search_data = () => {
  initChart1();
  initChart2();
  initChart3();
  initChart4();
  console.log(inspect_date.value);
};
// 重置
const resetSearch = () => {
  class_id.value = null;
  program_id.value = null;
  inspect_date.value = [null, null];
  all_class();
  initChart1();
  initChart2();
  initChart3();
  initChart4();
};
// 表格中响应式数据
const message1 = ref<string>("成绩分布");
const message2 = ref<string>("出勤率分布");
const message3 = ref<string>("学习进度追踪");
const message4 = ref<string>("内务分数排名");
const height1 = ref<string>("350px");
// 成绩分布的chart
const chartRef1 = ref<HTMLElement | null>(null);
let chartInstance1: echarts.ECharts | null = null;

const initChart1 = async () => {
  try {
    if (chartRef1.value !== null) {
      const response = await http.get("/api/analysis/score", {
        params: {
          class_id: class_id.value,
          program_id: program_id.value,
          exam_id: exam_id.value || classId
        },
      });
      const obj = response.data.results[0];
      const keys: string[] = Object.keys(obj);
      const values: number[] = Object.values(obj).map((value: any) =>
        parseInt(value, 10)
      );
      const chart1 = echarts.init(chartRef1.value);
      const option1 = {
        title: {
          text: "成绩分布统计",
          //   left: "center",
        },
        color: "#188df0",
        tooltip: {},
        xAxis: {
          data: keys,
        },
        yAxis: {},
        series: [
          {
            name: "数量",
            type: "bar",
            data: values,
          },
        ],
      };
      // 初始化或更新图表
      if (!chartInstance1) {
        chartInstance1 = echarts.init(chartRef1.value);
      }
      chartInstance1.setOption(option1);

      // 窗口自适应
      window.addEventListener("resize", () => chartInstance1?.resize());
      chart1.setOption(option1);
    }
  } catch (error) {
    console.error("请求失败:", error);
  }
};
// 考勤率趋势图
const chartRef2 = ref<HTMLElement | null>(null);

const initChart2 = async () => {
  try {
    if (chartRef2.value) {
      const response = await http.get("/api/analysis/attend", {
        params: {
          class_id: class_id.value,
          program_id: program_id.value,
          start_time: inspect_date.value[0],
          end_time: inspect_date.value[1],
        },
      });
      const chartData = response.data.results;
      const dates = chartData.map((item: any) => item.date);
      const rates = chartData.map((item: any) =>
        parseFloat(item.attendanceRate.replace("%", ""))
      );

      const chart2 = echarts.init(chartRef2.value);
      const option2 = {
        title: {
          text: "考勤率趋势分析",
        },
        color: "#67C23A",
        tooltip: {
          trigger: "axis",
          formatter: (params: any) => {
            const data = params[0];
            return `${data.axisValue}<br/>出勤率: ${data.value}%`;
          },
        },
        grid: {
          left: "3%",
          right: "4%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          data: dates,
          //   45度倾斜
          axisLabel: {
            rotate: 45,
          },
        },
        yAxis: {
          type: "value",
          min: 0,
          max: 100,
          axisLabel: {
            formatter: "{value}%",
          },
        },
        series: [
          {
            name: "出勤率",
            type: "line",
            smooth: true,
            data: rates,
            areaStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: "rgba(103, 194, 58, 0.6)" },
                { offset: 1, color: "rgba(103, 194, 58, 0.05)" },
              ]),
            },
            lineStyle: {
              width: 3,
            },
            itemStyle: {
              color: "#67C23A",
            },
          },
        ],
        dataZoom: [
          {
            type: "inside",
            start: 0,
            end: 100,
          },
        ],
      };

      chart2.setOption(option2);

      // 窗口自适应
      window.addEventListener("resize", () => {
        chart2.resize();
      });
    }
  } catch (error) {
    console.error("考勤数据加载失败:", error);
    message.error("考勤趋势数据加载失败");
  }
};

// 学习进度追踪图
// 学习进度构成分析图
const chartRef3 = ref<HTMLElement | null>(null);
let chartInstance3: echarts.ECharts | null = null;

const initChart3 = async () => {
  try {
    if (!chartRef3.value) return;

    // 获取数据
    const { data } = await http.get("/api/analysis/progress", {
      params: {
        class_id: class_id.value,
        program_id: program_id.value,
        start_time: inspect_date.value[0],
        end_time: inspect_date.value[1],
      },
    });
    const rawData = data.results;

    // 处理数据：计算每个学生总分
    const students = Object.keys(rawData);
    const scoreData = students
      .map((student) => {
        const totalScore = rawData[student].reduce(
          (sum: number, record: any) => sum + record.score,
          0
        );
        return {
          name: student,
          score: Number(totalScore.toFixed(2)), // 保留两位小数
        };
      })
      .sort((a, b) => b.score - a.score); // 降序排序
    // 动态计算纵轴最大值（加10分留出顶部空间）
    const maxScore = Math.max(...scoreData.map((d) => d.score)) + 10;
    // 配置图表选项
    const option = {
      //   title: {
      //     text: "学生成绩分布",
      //     left: "center",
      //     top: 20,
      //   },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: (params: any) => {
          const dataIndex = params[0].dataIndex;
          const student = scoreData[dataIndex];
          return `${student.name}<br/>总评分: <span style="color:#409EFF">${student.score}分</span>`;
        },
      },
      xAxis: {
        type: "category",
        data: scoreData.map((d) => d.name),
        axisLabel: {
          rotate: 45,
          width: 75,
          overflow: "truncate",
        },
      },
      yAxis: {
        type: "value",
        name: "评分（分）",
        min: 0, // 显式设置最小值
        max: maxScore, // 动态设置最大值
        axisLabel: {
          formatter: "{value} 分",
          color: "#333", // 确保标签颜色可见
          fontSize: 12,
        },
        splitLine: {
          // 添加网格线增强可读性
          show: true,
          lineStyle: {
            color: "#eee",
          },
        },
      },
      series: [
        {
          name: "总评分",
          type: "bar", // 恢复正确的图表类型
          data: scoreData.map((d) => d.score), // 转换为数值数组
          //   type: "line",
          smooth: true,
          //   data: scoreData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              { offset: 0, color: "#83bff6" },
              { offset: 0.5, color: "#188df0" },
              { offset: 1, color: "#188df0" },
            ]),
          },
          barWidth: "60%",
          label: {
            show: true,
            position: "top",
            formatter: "{c}分",
          },
        },
      ],
      dataZoom: [
        {
          type: "slider",
          start: 0,
          end: 100,
          top: "0%",
        },
      ],
    };

    // 初始化或更新图表
    if (!chartInstance3) {
      chartInstance3 = echarts.init(chartRef3.value);
      window.addEventListener("resize", () => chartInstance3?.resize());
    }
    chartInstance3.setOption(option);
  } catch (error) {
    console.error("成绩数据加载失败:", error);
    message.error("成绩分布数据加载失败");
  }
};

// 内务分数统计图
const chartRef4 = ref<HTMLElement | null>(null);
let chartInstance4: echarts.ECharts | null = null;

const initChart4 = async () => {
  try {
    if (!chartRef4.value) return;

    // 获取数据
    const { data } = await http.get("/api/analysis/housekeep", {
      params: {
        class_id: class_id.value,
        program_id: program_id.value,
        start_time: inspect_date.value[0],
        end_time: inspect_date.value[1],
      },
    });
    const rawData = data.results;

    // 处理数据：排序并转换为适合条形图的格式
    const chartData = rawData
      .sort((a: any, b: any) => b.score - a.score) // 从高到低排序
      .map((item: any) => ({
        name: item.inspect_num.toString(), // 检查编号作为名称
        value: item.score, // 分数作为值
      }));

    // 配置选项
    const option = {
      title: {
        text: "宿舍内务分数排行",
        left: "center",
      },
      tooltip: {
        trigger: "axis",
        axisPointer: {
          type: "shadow",
        },
        formatter: (params: any) => {
          const data = params[0].data;
          return `检查编号: ${data.name}<br/>分数: <span style="color:#67C23A">${data.value}分</span>`;
        },
      },
      grid: {
        left: "10%", // 留出空间显示长标签
        right: "5%",
      },
      xAxis: {
        type: "value",
        // name: '分数',
        min: 0,
        max: 100,
        axisLabel: {
          formatter: "{value} 分",
        },
      },
      yAxis: {
        type: "category",
        data: chartData.map((d) => d.name),
        axisLabel: {
          color: "#333",
          width: 80,
          overflow: "truncate",
        },
        axisTick: {
          show: false,
        },
      },
      series: [
        {
          name: "内务分数",
          type: "bar",
          data: chartData,
          itemStyle: {
            color: new echarts.graphic.LinearGradient(1, 0, 0, 0, [
              { offset: 0, color: "#67C23A" }, // 右端颜色
              { offset: 1, color: "#85CE61" }, // 左端颜色
            ]),
            borderRadius: [0, 8, 8, 0], // 右侧圆角
          },
          barWidth: "60%",
          label: {
            show: true,
            position: "right",
            color: "#67C23A",
            fontWeight: "bold",
            formatter: "{c}分",
          },
        },
      ],
    };

    // 初始化图表
    if (!chartInstance4) {
      chartInstance4 = echarts.init(chartRef4.value);
      window.addEventListener("resize", () => chartInstance4?.resize());
    }
    chartInstance4.setOption(option);
  } catch (error) {
    console.error("内务数据加载失败:", error);
    message.error("内务分数数据加载失败");
  }
};
// 初始化调用
onMounted(() => {
  initChart1();
  initChart2();
  initChart3();
  initChart4();
  all_class();
  all_program();
  get_exams()
});
</script>

<style scoped>
.chart1 {
  display: flex;
  justify-content: space-between;
  margin-top: 20px;
}
.chart2 {
  display: flex;
  justify-content: space-between;
  margin-top: 10px;
}
</style>